//package wmmd.disc.webmaster;

import java.io.*;
//import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import db.DatabaseConnector;

public class SubmitPost extends HttpServlet {
    
    String db = "";
    String mID = "";
    String tName = "";
    
//doPost method included for POST requests
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        doGet(request, response);
    }
    
//This subroutine is called from SubmitPost.jsp
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        //The JSP document passes in which db table to use
        db = request.getParameter("db");
        tName = request.getParameter("tName");
        mID = request.getParameter("mID");
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        try {
            //Variables for updating the db.
            String UpdateStr = "";
            StringBuffer sb = new StringBuffer("");
            
            Enumeration RSparams = request.getParameterNames();
            while (RSparams.hasMoreElements()) {
                String name = (String)RSparams.nextElement();
                String value = request.getParameter(name);
                if(name.startsWith("DISC")) {
                    //UpdateStr += name.substring(4, name.length()) + " = ";
                    UpdateStr += name.substring(4, name.length()) + " = ?, ";
                    sb.append(value.replace('\'', '`')+"'");
                }
            }
            sb.deleteCharAt(sb.length()-1); //delete trailing '
            UpdateStr = UpdateStr.substring(0, UpdateStr.length()-2);
            
            //for debugging
            //out.println("<p>UpdateStr: " + UpdateStr + "</p>\n");
            
            // Post the question to the appropriate db table
            WriteMessageTable(response, UpdateStr,sb.toString().split("'"));
            
        } catch (Exception e) {
            out.println(e.getMessage());
        }
    }
    
    // Writes the record to the questions table, returning the ID of the new record
    public void WriteMessageTable(HttpServletResponse response, String UpdateStr, Object[] var)
    throws IOException {
        
        //Variables for the database connection
        DatabaseConnector con = new DatabaseConnector(DatabaseConnector.getDatabaseType());
        //Statement stmt = null;
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        //try {
            //Set the database connection
            //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            
            //String database = "jdbc:odbc:" + db;
            //con = new DatabaseConnector(DatabaseConnector.getDatabaseType());
            //stmt = con.createStatement();

            //TODO: Update
            //String updateString = "UPDATE " + tName + " SET " + UpdateStr + " WHERE ID = " + mID;
            Object[] allVar = new Object[var.length+1];
            for (int i=0;i<var.length;i++){
                allVar[i] = var[i];
            } allVar[allVar.length] = mID;
            String updateString = "UPDATE " + tName + " SET " + UpdateStr + " WHERE ID = ?";
            con.freeformSQL(updateString, allVar);
            //String updateString = "UPDATE " + tName + " SET " + UpdateStr + " WHERE ID = " + mID;
            
            //for debugging
            //out.println("<p>WriteMessageUpdateStr: " + updateString + "</p>\n");
            
            //stmt.executeUpdate(updateString);
            //con.close();
            
            //Send back confirmation
            DisplayRecord(response, mID);
            
        /*} catch (ClassNotFoundException e) {
            out.println("Couldn't load database driver: " + e.getMessage());
        } catch (SQLException e) {
            out.println("SQLException caught in WriteQuestionTable: " + e.getMessage());
        } finally {
            try {
                if (con != null) {con.close();}
            } catch (SQLException ignored) {}
        }*/
    }
    
    public void DisplayRecord(HttpServletResponse response, String id)
    throws IOException {
        
        //Variables for the database connection
        DatabaseConnector con = new DatabaseConnector(DatabaseConnector.getDatabaseType());
        DatabaseConnector con2 = new DatabaseConnector(DatabaseConnector.getDatabaseType());
        //Statement stmt = null;
        //ResultSet rs = null;
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        //try {
            //Set the database connection
            //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            
            //String database = "jdbc:odbc:" + db;
            //con = new DatabaseConnector(DatabaseConnector.getDatabaseType());
            //stmt = con.createStatement();

            //TODO: Query
            //rs = stmt.executeQuery("SELECT * FROM " + tName + " WHERE ID = " + id);
            //ResultSetMetaData rsmd = rs.getMetaData();
            //int numColumns = rsmd.getColumnCount();
            
            // Confirm the submission
            out.println("<div class=\"h3\">Message Updated Successfully</div>");
            out.print("<p>The message has been updated successfully. ");
            out.print("Here is what was updated in the database:</p>");

            // Create the header for the resource info
            out.println("<table border=\"0\" cellpadding=\"3\" width=\"615\">");
            out.print("<tr><td bgcolor=\"cccccc\">");
            out.println("<b>Message Information</b>");
            out.println("</td></tr></table>");

            String SQL = "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME in ('"+tName+"')";
            String col[][] = con2.selectSQL(SQL, 1);
            SQL = "SELECT * FROM "+tName+" WHERE ID = ?";
            String[][] rs = con.selectSQL(SQL,col.length,new Object[]{id});

            for (int i=0;i<rs.length;i++){
                for (int j=0;j<col.length;j++){
                    if(rs[j][i]!=null && rs[j][i].length() > 0) {
                        out.println("<b>" + col[j][i] + ":</b> " + rs[j][i].replace('|', ',') + "<br>");
                    }
                }
            }

            //TODO: Query

            /*rs = stmt.executeQuery("SELECT * FROM " + tName + " WHERE ID = " + id);
            ResultSetMetaData rsmd = rs.getMetaData();
            int numColumns = rsmd.getColumnCount();*/
            
            //Display the contents
            /*while(rs.next()) {
                // Get the column names; column indices start from 1
                for (int i=1; i<numColumns+1; i++) {
                    String columnName = rsmd.getColumnName(i);
                    String valueString = rs.getString(columnName);
                    
                    if(valueString!=null && valueString.length() > 0) {
                        out.println("<b>" + columnName + ":</b> " + valueString.replace('|', ',') + "<br>");
                    }
                }
            }
        /*} catch (ClassNotFoundException e) {
            out.println("Couldn't load database driver: " + e.getMessage());
        } catch (SQLException e) {
            out.println("SQLException caught in DisplayRecord: " + e.getMessage());
        } finally {
            try {
                if (con != null) {con.close();}
            } catch (SQLException ignored) {}
        }*/
    }
    
}
